//
//  ImageFullScreenViewController.m
//  SecretRoom
//
//  Created by Sitdhibhong Laokok on 9/5/54 BE.
//  Copyright 2554 App Tree. All rights reserved.
//

#import "ImageFullScreenViewController.h"

#import "ImageDetailsViewController.h"

@implementation ImageFullScreenViewController

@synthesize event = _event;
@synthesize evidenceFectchedResultController = _evidenceFectchedResultController;
@synthesize evidence = _evidence;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithEvidence:(Evidence *)evd forEvent:(Event *)evt
{
    if (self = [super init]) {
//        self.event = evt;
        self.evidence = evd;
        
        NSString *imageURL = [SLCommonsFileUtility evidenceURLResolvedWithEvidence:self.evidence 
                                                                           inEvent:self.event];
        
        BOOL isDirectory;
        BOOL isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:imageURL isDirectory:&isDirectory];
        if (!isDirectory && isFileExists) {
            NSLog(@"Image url: %@", imageURL);
            imageData = [UIImage imageWithContentsOfFile:imageURL];
        } else {
            NSLog(@"File does not exists, use for blank: %@", imageURL);
            imageData = [UIImage imageNamed:@"BlankForEvidence.png"];
        }

    }
    
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
- (void)loadView
{
    [super loadView];
    
    
    NSLog(@"%@", self.evidence);
    
    UIBarButtonItem *flexibleWidthButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    UIBarButtonItem *actionDelete = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(showImageActions)];
    
    UIBarButtonItem *detailsButton = [[UIBarButtonItem alloc] initWithTitle:@"Details..." style:UIBarButtonItemStyleBordered target:self action:@selector(imageDetails)];
    
    self.navigationItem.rightBarButtonItem = detailsButton;
    
    self.toolbarItems = [NSArray arrayWithObjects:flexibleWidthButton, actionDelete, nil];
    
    [flexibleWidthButton release];
    [actionDelete release];
    [detailsButton release];
    
    self.navigationController.toolbar.barStyle = UIBarStyleBlackTranslucent;
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    
    [self performSelectorOnMainThread:@selector(imageRefine) withObject:nil waitUntilDone:YES];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    
    [self setEvent:nil];
    [self setEvidence:nil];
    
    [self setEvidenceFectchedResultController:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent animated:YES];
    [self.view setBackgroundColor:[UIColor blackColor]];
    
    NSError *error = nil;
    [self.evidenceFectchedResultController performFetch:&error];
    
    if (error != nil) {
        NSLog(@"%s Error while fetching evidence details: %@", __PRETTY_FUNCTION__, [error localizedDescription]);
        
    } else {
        NSLog(@"Will appear");
        Evidence *fetchedEvidence = [self.evidenceFectchedResultController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        
        NSLog(@"Number of me: %@", [self.evidenceFectchedResultController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]);
        
        self.title = (fetchedEvidence.evidenceName != nil) ? [NSString stringWithFormat:@"%@", fetchedEvidence.evidenceName] : [NSString stringWithFormat:@"%@", fetchedEvidence.filename] ;
    }
    
}

- (void)dealloc
{
    [_event release];
    [_evidence release];
    [evidenceFectchedResultController release];
    [evidenceImageViewDisplay release];
//    [imageData release];
    
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView 
{
    return evidenceImageViewDisplay;
}

#pragma mark - Class accessor override
- (NSFetchedResultsController *)evidenceFectchedResultController
{
    if (_evidenceFectchedResultController != nil) {
        return _evidenceFectchedResultController;
    }
    
    NSFetchRequest *fethRequest = [[NSFetchRequest alloc] init];
    fethRequest.entity = [NSEntityDescription entityForName:@"Evidence" inManagedObjectContext:[[SRConnectionControlCenter sharedInstance] manageObjectContext]];
    fethRequest.sortDescriptors = [NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"datetimeCollected" ascending:NO], nil];
    fethRequest.predicate = [NSPredicate predicateWithFormat:@"self = %@", self.evidence];
    
    NSFetchedResultsController *fetchResultControl = [[NSFetchedResultsController alloc] initWithFetchRequest:fethRequest managedObjectContext:[[SRConnectionControlCenter sharedInstance] manageObjectContext] sectionNameKeyPath:nil cacheName:nil];
    
    self.evidenceFectchedResultController = fetchResultControl;
    
    [fethRequest release];
    [fetchResultControl release];
    
    return _evidenceFectchedResultController;
}

#pragma mark - Implement defined method

- (void)imageRefine
{
    evidenceImageViewDisplay = [[UIImageView alloc] initWithImage:imageData];
    evidenceImageViewDisplay.frame = [UIScreen mainScreen].bounds; // CGRectMake(0, 0, imageData.size.width, imageData.size.height);
    evidenceImageViewDisplay.contentMode = UIViewContentModeScaleAspectFit;
    evidenceImageViewDisplay.autoresizingMask = (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
    evidenceImageViewDisplay.backgroundColor = [UIColor blackColor];
    
//    float ratio = imageData.size.width/[[UIScreen mainScreen] bounds].size.width;
//    CGRect imageFrame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, (imageData.size.height / ratio));
//    evidenceImageViewDisplay.frame = imageFrame;
    
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
    scrollView.contentMode = UIViewContentModeScaleAspectFit;
    [evidenceImageViewDisplay sizeToFit];
    scrollView.contentSize = CGSizeMake(evidenceImageViewDisplay.bounds.size.width, evidenceImageViewDisplay.bounds.size.height);
    scrollView.autoresizingMask = (UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight);
    scrollView.maximumZoomScale = 4.0;
    scrollView.minimumZoomScale = 1;
    scrollView.clipsToBounds = YES;
    scrollView.delegate = self;
    scrollView.scrollEnabled = YES;
    
    [scrollView addSubview:evidenceImageViewDisplay];
    
    [self.view addSubview:scrollView];
    
    [scrollView release];
}

- (void)showImageActions
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Delete" otherButtonTitles:nil];
    [actionSheet showFromToolbar:self.navigationController.toolbar];
    
    [actionSheet release];
}

- (void)imageDetails
{
    ImageDetailsViewController *idvc = [[ImageDetailsViewController alloc] initWithStyle:UITableViewStyleGrouped];
    
    idvc.evidenceToBeDisplayed = self.evidence;
    
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:idvc];
    
    [navController setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
    [self presentModalViewController:navController animated:YES];
    
    [idvc release];
    [navController release];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != actionSheet.cancelButtonIndex)  {
        UIAlertView *deleteWarning = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@", self.title] message:@"Are you sure for delete this image ?" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Delete", nil];
        [deleteWarning show];
        [deleteWarning release];
    }
}

#pragma mark - UIAlertDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != alertView.cancelButtonIndex) {
        [[[SRConnectionControlCenter sharedInstance] manageObjectContext] deleteObject:self.evidence];
        [self.navigationController popViewControllerAnimated:YES];
    }
}
@end
